package com.xspace.android.imcommon.http;

import android.util.Log;

import com.xspace.android.imcommon.entity.ChatMsg;
import com.xspace.android.imcommon.utils.ImConstants;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.InputStream;

public class UploadFileTask implements NetworkListener {
	public final static int UPLOADFILE_CONTENTTYPE_IMAGE = 0;
	public final static int UPLOADFILE_CONTENTTYPE_VOICE = 1;
	public final static int UPLOADFILE_CONTENTTYPE_VIDEO = 2;
	private IRequestResult iRequestResult;
	private ChatMsg info;

	public UploadFileTask(IRequestResult iRequestResult, ChatMsg info) {
		this.iRequestResult = iRequestResult;
		this.info = info;
	}

	public void startUploadFile(String content, int contentType,String name) {
		String uploadUrl=ImConstants.getUploadUrl();
		Log.i("uploadfile", "startUploadFile >>"+uploadUrl);
		ConnectorImpl conn = new ConnectorImpl(uploadUrl, buildUploadFileRequestProtocol(content, contentType,name), this, ConnectorImpl.POST);
		ThreadPoolWrap.getThreadPool().executeTask(conn);
	}

	private String buildUploadFileRequestProtocol(String content, int contentType,String name) {
		//String request = "{uuid:\"" + info.mUUID + "\",content:\"" + content + "\",content_type:\"" + contentType +  "\",name:\"" +name + "\"}";
		JSONObject json=new JSONObject();
		try {
			json.put("uuid", info.mUUID);
			json.put("content_type", ""+contentType);
			json.put("name", name);
			json.put("content", content);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		//String request =json.toString();
		LogUtils.d("**********s***url:" +info.mUUID+ ImConstants.getUploadUrl());

		return json.toString();
	}

	@Override
	public void action(int actionCode, Object object) {
		switch (actionCode) {
		case NetworkListener.RECEIVE_STREAM:
			int returnCode = -1;
			String returnRes = "";
			try {
				String returnStr = AppUtils.parser((InputStream) object);
				LogUtils.d("**********returnStr***" + returnStr);
				JSONTokener jsonParser = new JSONTokener(returnStr);
				JSONObject returnObj = null;
				returnObj = (JSONObject) jsonParser.nextValue();
				returnCode = returnObj.getInt("code");
				returnRes = returnObj.getString("desc");

			} catch (Exception e) {
				e.printStackTrace();
			}
			iRequestResult.requestResult(returnCode, returnRes, info);
			break;
		default:
			iRequestResult.requestResult(actionCode, "", info);
			break;
		}
	}

}
